{% extends "admin/layout.html" %}

{% block title %}供应商管理 - {{ system_config.site_name|default('项目管理系统') }}{% endblock %}

{% block content %}
    <div class="container-fluid">
        <div class="d-flex justify-content-between align-items-center mb-4">
            <div>
                <h1 class="h3 mb-0">供应商管理</h1>

            </div>
            <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#supplierModal" onclick="resetForm()">
                <i class="fas fa-plus me-1"></i> 新增供应商
            </button>
        </div>

        <!-- 消息提示 -->
        {% with messages = get_flashed_messages(with_categories=true) %}
            {% if messages %}
                {% for category, message in messages %}
                    <div class="alert alert-{{ 'danger' if category == 'error' else 'success' }} alert-dismissible fade show" role="alert">
                        {{ message }}
                        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                    </div>
                {% endfor %}
            {% endif %}
        {% endwith %}

        <div class="card">
            <div class="card-header">
                <h5 class="card-title mb-0">供应商列表</h5>
            </div>
            <div class="card-body p-0">
                <div class="table-responsive">
                    <table class="table table-hover mb-0">
                        <thead class="table-light">
                        <tr>
                            <th>供应商名称</th>
                            <th>联系人</th>
                            <th>联系电话</th>
                            <th>邮箱</th>
                            <th>地址</th>
                            <th>状态</th>
                            <th>创建时间</th>
                            <th>操作</th>
                        </tr>
                        </thead>
                        <tbody>
                        {% for supplier in suppliers %}
                            <tr>
                                <td>
                                    <strong>{{ supplier.name }}</strong>
                                    {% if supplier.website %}
                                        <br><small class="text-muted">{{ supplier.website }}</small>
                                    {% endif %}
                                </td>
                                <td>{{ supplier.contact_person or '-' }}</td>
                                <td>{{ supplier.contact_phone or '-' }}</td>
                                <td>{{ supplier.contact_email or '-' }}</td>
                                <td>
                                    {% if supplier.address %}
                                        <span title="{{ supplier.address }}">
                                    {{ supplier.address[:20] }}{% if supplier.address|length > 20 %}...{% endif %}
                                </span>
                                    {% else %}
                                        -
                                    {% endif %}
                                </td>
                                <td>
                                <span class="badge {% if supplier.is_active %}bg-success{% else %}bg-secondary{% endif %}">
                                    {{ '启用' if supplier.is_active else '停用' }}
                                </span>
                                </td>
                                <td>
                                    {% if supplier.created_at %}
                                        <small class="text-muted">{{ supplier.created_at.strftime('%Y-%m-%d') }}</small>
                                    {% else %}
                                        -
                                    {% endif %}
                                </td>
                                <td>
                                    <div class="btn-group btn-group-sm">
                                        <button type="button" class="btn btn-outline-primary"
                                                onclick="editSupplier({{ supplier.id }})">
                                            <i class="fas fa-edit"></i>
                                        </button>
 {% if supplier.is_active %}
    <button type="button" class="btn btn-outline-success"
            onclick="toggleSupplier({{ supplier.id }}, false)"
            data-bs-toggle="tooltip" title="点击停用">
        <i class="fas fa-toggle-on me-1"></i>
    </button>
{% else %}
    <button type="button" class="btn btn-outline-secondary"
            onclick="toggleSupplier({{ supplier.id }}, true)"
            data-bs-toggle="tooltip" title="点击启用">
        <i class="fas fa-toggle-off me-1"></i>
    </button>
{% endif %}
                                        <!-- 添加删除按钮 -->
                                        <button type="button" class="btn btn-outline-dark"
                                                onclick="deleteSupplier({{ supplier.id }})">
                                            <i class="fas fa-trash"></i>
                                        </button>
                                    </div>
                                </td>
                            </tr>
                        {% else %}
                            <tr>
                                <td colspan="8" class="text-center py-4 text-muted">
                                    <i class="fas fa-truck fa-2x mb-2"></i>
                                    <p>暂无供应商数据</p>
                                    <button type="button" class="btn btn-primary btn-sm" data-bs-toggle="modal" data-bs-target="#supplierModal">
                                        <i class="fas fa-plus me-1"></i> 添加第一个供应商
                                    </button>
                                </td>
                            </tr>
                        {% endfor %}
                        </tbody>
                    </table>
                </div>
            </div>
            {% if suppliers %}
                <div class="card-footer">
                    <div class="d-flex justify-content-between align-items-center">
                        <div class="text-muted">
                            共 {{ suppliers|length }} 个供应商
                        </div>
                        <div>
                            <button type="button" class="btn btn-outline-secondary btn-sm" onclick="exportSuppliers()">
                                <i class="fas fa-download me-1"></i> 导出
                            </button>
                        </div>
                    </div>
                </div>
            {% endif %}
        </div>
    </div>

    <!-- 供应商编辑模态框 -->
    <div class="modal fade" id="supplierModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="supplierModalTitle">新增供应商</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <form id="supplierForm" method="post" action="{{ url_for('asset.supplier_list') }}">
                    <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
                    <input type="hidden" id="supplier_id" name="supplier_id" value="">
                    <div class="modal-body">
                        <div class="mb-3">
                            <label for="supplier_name" class="form-label">供应商名称 <span class="text-danger">*</span></label>
                            <input type="text" class="form-control" id="supplier_name" name="name" required maxlength="100">
                            <div class="form-text">请输入供应商的完整名称</div>
                        </div>
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label for="contact_person" class="form-label">联系人</label>
                                <input type="text" class="form-control" id="contact_person" name="contact_person" maxlength="50">
                            </div>
                            <div class="col-md-6 mb-3">
                                <label for="contact_phone" class="form-label">联系电话</label>
                                <input type="tel" class="form-control" id="contact_phone" name="contact_phone" maxlength="20">
                            </div>
                        </div>
                        <div class="mb-3">
                            <label for="contact_email" class="form-label">联系邮箱</label>
                            <input type="email" class="form-control" id="contact_email" name="contact_email" maxlength="100">
                        </div>
                        <div class="mb-3">
                            <label for="address" class="form-label">地址</label>
                            <textarea class="form-control" id="address" name="address" rows="2" maxlength="200"></textarea>
                        </div>
                        <div class="mb-3">
                            <label for="website" class="form-label">网站</label>
                            <input type="url" class="form-control" id="website" name="website" placeholder="https://" maxlength="200">
                        </div>
                        <div class="mb-3">
                            <div class="form-check form-switch">
                                <input class="form-check-input" type="checkbox" id="is_active" name="is_active" checked>
                                <label class="form-check-label" for="is_active">启用该供应商</label>
                            </div>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                        <button type="submit" class="btn btn-primary" id="submitBtn">保存</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <script>
        // 全局变量存储供应商数据
        let suppliersData = {};

        // 页面加载时获取供应商数据
        document.addEventListener('DOMContentLoaded', function() {
            // 从后端获取供应商数据（如果需要）
            fetchSuppliersData();
        });

        // 获取供应商数据
        function fetchSuppliersData() {
            // 这里可以通过AJAX从后端获取详细数据
            // 暂时使用页面已有的数据
            {% for supplier in suppliers %}
                suppliersData[{{ supplier.id }}] = {
                    name: {{ supplier.name|tojson }},
                    contact_person: "{{ supplier.contact_person|escapejs if supplier.contact_person else '' }}",
                    contact_phone: "{{ supplier.contact_phone|escapejs if supplier.contact_phone else '' }}",
                    contact_email: "{{ supplier.contact_email|escapejs if supplier.contact_email else '' }}",
                    address: "{{ supplier.address|escapejs if supplier.address else '' }}",
                    website: "{{ supplier.website|escapejs if supplier.website else '' }}",
                    is_active: {{ 'true' if supplier.is_active else 'false' }}
                };
            {% endfor %}
        }

        // 编辑供应商
        function editSupplier(supplierId) {
            const supplier = suppliersData[supplierId];
            if (!supplier) {
                showAlert('error', '未找到供应商数据');
                return;
            }

            // 填充表单数据
            document.getElementById('supplier_id').value = supplierId;
            document.getElementById('supplier_name').value = supplier.name;
            document.getElementById('contact_person').value = supplier.contact_person;
            document.getElementById('contact_phone').value = supplier.contact_phone;
            document.getElementById('contact_email').value = supplier.contact_email;
            document.getElementById('address').value = supplier.address;
            document.getElementById('website').value = supplier.website;
            document.getElementById('is_active').checked = supplier.is_active;

            // 更新模态框标题
            document.getElementById('supplierModalTitle').textContent = '编辑供应商';

            // 显示模态框
            const modal = new bootstrap.Modal(document.getElementById('supplierModal'));
            modal.show();
        }

        // 切换供应商状态
        function toggleSupplier(supplierId, newStatus) {
            const action = newStatus ? '启用' : '停用';
            const supplierName = suppliersData[supplierId]?.name || '该供应商';

            if (confirm(`确定要${action}「${supplierName}」吗？`)) {
                // 发送AJAX请求
                fetch(`{{ url_for('asset.supplier_list') }}/${supplierId}/toggle`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-Requested-With': 'XMLHttpRequest',
                        'X-CSRFToken': '{{ csrf_token() }}'
                    },
                    body: JSON.stringify({
                        is_active: newStatus
                    })
                })
                    .then(response => response.json())
                    .then(data => {
                        if (data.success) {
                            showAlert('success', data.message);
                            // 刷新页面
                            setTimeout(() => {
                                window.location.reload();
                            }, 1000);
                        } else {
                            showAlert('error', data.message);
                        }
                    })
                    .catch(error => {
                        console.error('Error:', error);
                        showAlert('error', '操作失败，请重试');
                    });
            }
        }

        // 重置表单（新增时使用）
        function resetForm() {
            document.getElementById('supplierForm').reset();
            document.getElementById('supplier_id').value = '';
            document.getElementById('supplierModalTitle').textContent = '新增供应商';
            document.getElementById('is_active').checked = true;
        }

        // 导出供应商数据
        function exportSuppliers() {
            // 实现导出功能
            window.location.href = '{{ url_for("asset.supplier_list") }}?export=excel';
        }

        // 显示提示消息
        function showAlert(type, message) {
            const alertClass = type === 'success' ? 'alert-success' : 'alert-danger';
            const alertHtml = `
        <div class="alert ${alertClass} alert-dismissible fade show" role="alert">
            ${message}
            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        </div>
    `;

            // 插入到页面顶部
            const container = document.querySelector('.container-fluid');
            const firstChild = container.firstElementChild;
            container.insertAdjacentHTML('afterbegin', alertHtml);

            // 3秒后自动消失
            setTimeout(() => {
                const alert = document.querySelector('.alert');
                if (alert) {
                    alert.remove();
                }
            }, 3000);
        }

        // 表单提交处理
        document.getElementById('supplierForm').addEventListener('submit', function(e) {
            const submitBtn = document.getElementById('submitBtn');
            submitBtn.disabled = true;
            submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin me-1"></i> 保存中...';

            // 可以在这里添加表单验证
            const name = document.getElementById('supplier_name').value.trim();
            if (!name) {
                e.preventDefault();
                showAlert('error', '供应商名称不能为空');
                submitBtn.disabled = false;
                submitBtn.innerHTML = '保存';
                return;
            }
        });

        // 模态框隐藏时重置表单
        document.getElementById('supplierModal').addEventListener('hidden.bs.modal', function() {
            resetForm();
        });

        // 删除供应商
        function deleteSupplier(supplierId) {
            const supplierName = suppliersData[supplierId]?.name || '该供应商';

            if (confirm(`确定要删除「${supplierName}」吗？此操作不可恢复！`)) {
                fetch(`{{ url_for('asset.supplier_list') }}/${supplierId}/delete`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-Requested-With': 'XMLHttpRequest',
                        'X-CSRFToken': '{{ csrf_token() }}'
                    }
                })
                    .then(response => response.json())
                    .then(data => {
                        if (data.success) {
                            showAlert('success', data.message);
                            // 刷新页面
                            setTimeout(() => {
                                window.location.reload();
                            }, 1000);
                        } else {
                            showAlert('error', data.message);
                        }
                    })
                    .catch(error => {
                        console.error('Error:', error);
                        showAlert('error', '删除失败，请重试');
                    });
            }
        }
    </script>

    <style>
        .form-switch .form-check-input {
            width: 3em;
            height: 1.5em;
        }
        .form-switch .form-check-input:checked {
            background-color: #198754;
            border-color: #198754;
        }
        .table th {
            border-top: none;
            font-weight: 600;
        }
    </style>
{% endblock %}